package com.transcargo.action;

import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.transcargo.errors.ErrorList;
import com.transcargo.db.db;
import com.transcargo.db.dbException;

public class EditTruckNameAction extends AuthAction {
	String id = "";
	String name = "";
    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
		id = request.getParameter("id");
		name = request.getParameter("name");
		if (id == null || id.length() == 0 || Integer.parseInt(id) == 0) throw new ServletParametersException();
    }
    private void servletValidateValues() throws ServletValidationException {
		if (name == null || name.length() == 0) throw new ServletValidationException(ErrorList.ERROR_STR_TRUCKNAME_MISSING);
		if (name.length() > 255) throw new ServletValidationException(ErrorList.ERROR_STR_TRUCKNAME_TOO_LONG);
    }
    private void servletExecuteAction() throws ServletActionException {
		int Id = Integer.parseInt(id);
        try {
		    list = dbase.execute("SELECT name FROM transport WHERE id=" + Integer.toString(Id) + " and user_id=" + Integer.toString(User_Id));
		    if (list != null) iter = list.iterator();
		    if (iter.hasNext()) {
		        String[] str = iter.next();
		        String old_name = str[0];
		        if (!old_name.equals(name)) {
		            db.PreStatement pre = null;
					pre = dbase.CreateStatement("UPDATE transport SET name=? WHERE id=? AND user_id=?");
		            pre.Insert(name);
					pre.Insert(Id);
					pre.Insert(User_Id);
		            dbase.executeUpdate(pre);
		        }
		    }
		} catch (dbException e) {
			System.out.println("Db exception: " + e.getMessage());
			throw new ServletActionException();
		} catch (SQLException e) {
			System.out.println("SQL exception: " + e.getMessage());
			throw new ServletActionException();
		}
    }
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		try {
            servletGetValues(request);
            servletValidateValues();
            servletExecuteAction();
            sendRedirect(response, "trucks.jsp");
	    } catch (ServletParametersException e) {
            if (e.getMessage() != null) {
                sendError(response, new Exception(e.getMessage()));
            } else {
                sendRedirect(response, "trucks.jsp");
            }
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletActionException e) {
            sendError(response, new Exception("" + ErrorList.ERROR_STR_GENERIC + dbase.getError()));
        }
    }
}
